import React, {useRef, forwardRef, useImperativeHandle} from 'react'

function TextInputWithFocusButton(props) {
  const inputRef = useRef()
  const onButtonClick = () => {
    // `current` 指向已挂载到 DOM 上的文本输入元素
    inputRef.current.focus123()
  };
  console.log(inputRef.current, 'inputRef.current');
  return (
    <>
      <FancyInput ref={inputRef} />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  )
}

function FancyInput(props, ref) {
  const inputRef = useRef();
  useImperativeHandle(ref, () => ({
    focus123: () => {
      inputRef.current.focus();
      inputRef.current.value = 1234
    }
  }));
  return <input ref={inputRef} />
}
FancyInput = forwardRef(FancyInput)

export default TextInputWithFocusButton